
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/login/iview/user_perfect_iview.dart';
import 'package:flutter_deer/login/presenter/user_perfect_presenter.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/routers/routers.dart';
import 'package:flutter_deer/util/change_notifier_manage.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/widgets/my_app_bar.dart';
import 'package:flutter_deer/widgets/my_button.dart';
import 'package:flutter_deer/widgets/my_scroll_view.dart';
import 'package:flutter_deer/widgets/selected_image.dart';
import 'package:flutter_deer/widgets/text_field_item.dart';
import 'package:image_picker/image_picker.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';

class UserInfoAuditPage extends StatefulWidget {
  const UserInfoAuditPage({super.key});

  @override
  _UserInfoAuditPageState createState() => _UserInfoAuditPageState();
}

class _UserInfoAuditPageState extends State<UserInfoAuditPage> with BasePageMixin<UserInfoAuditPage, PowerPresenter<dynamic>>, AutomaticKeepAliveClientMixin<UserInfoAuditPage>,ChangeNotifierMixin<UserInfoAuditPage> implements UserPerfectIMvpView {
  final GlobalKey<SelectedImageState> _imageGlobalKey = GlobalKey<SelectedImageState>();
  final TextEditingController _nickNameController = TextEditingController();
  final FocusNode _nodeText1 = FocusNode();
  final ImagePicker picker = ImagePicker();
  bool _clickable = false;
  @override
  bool get wantKeepAlive => true;

  late UserPerfectPagePresenter userPerfectPagePresenter;

  @override
  void perfectResult(bool? result){
    if(result==true){
      SpUtil.putString(Constant.perfect, "1");
      NavigatorUtils.push(context, Routes.home, clearStack: true);
    }else{
      Toast.show('${DeerLocalizations.of(context)!.saveFail.nullSafe}');
    }
  }

  @override
  Map<ChangeNotifier, List<VoidCallback>?>? changeNotifier() {
    final List<VoidCallback> callbacks = <VoidCallback>[_verify];
    return <ChangeNotifier, List<VoidCallback>?>{
      _nickNameController: callbacks,
      _nodeText1: null,
    };
  }

  void _verify() {
    final String nickName = _nickNameController.text;
    bool clickable = true;
    if (nickName.isEmpty || nickName.length < 1) {
      clickable = false;
    }
    if(SpUtil.containsKey(Constant.tempUserAvatarUrl)==false||SpUtil.getString(Constant.tempUserAvatarUrl).nullSafe.isEmpty){
      clickable = false;
    }
    /// 状态不一样再刷新，避免不必要的setState
    if (clickable != _clickable) {
      setState(() {
        _clickable = clickable;
      });
    }
  }

  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(this);
    userPerfectPagePresenter = new UserPerfectPagePresenter();
    powerPresenter.requestPresenter([userPerfectPagePresenter]);
    return powerPresenter;
  }

  KeyboardActionsConfig _buildConfig(BuildContext context) {
    return KeyboardActionsConfig(
      keyboardActionsPlatform: KeyboardActionsPlatform.IOS,
      keyboardBarColor: ThemeUtils.getKeyboardActionsColor(context),
      actions: [
        KeyboardActionsItem(
          focusNode: _nodeText1,
          displayDoneButton: false,
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: '${DeerLocalizations.of(context)!.personalInformation.nullSafe}',
      ),
      body: MyScrollView(
        padding: const EdgeInsets.symmetric(vertical: 16.0),
        keyboardConfig: _buildConfig(context),
        tapOutsideToDismiss: true,
        bottomButton: Padding(
          padding: const EdgeInsets.only(left: 16.0, right: 16.0, bottom: 8.0),
          child: MyButton(
            onPressed: _clickable?_submit:null,
            text: '${DeerLocalizations.of(context)!.submit.nullSafe}',
          ),
        ),
        children: _buildBody(),
      ),

      /// 同时存在底部按钮与keyboardConfig配置时，为保证Android与iOS平台软键盘弹出高度正常，添加下面的代码。
      resizeToAvoidBottomInset: defaultTargetPlatform != TargetPlatform.iOS,
    );
  }

  void _submit() {
    String avatarUrl = SpUtil.getString(Constant.tempUserAvatarUrl).nullSafe;
    userPerfectPagePresenter.updateUserPerfect(avatarUrl, _nickNameController.text.nullSafe);
  }

  List<Widget> _buildBody() {
    return [
      Gaps.vGap5,
      Padding(
        padding: EdgeInsets.only(left: 16.0),
        child: Text('${DeerLocalizations.of(context)!.personalIdentityInformation.nullSafe}', style: TextStyles.textBold18),
      ),
      Gaps.vGap16,
      Center(
        child: SelectedImage(
          key: _imageGlobalKey,
        ),
      ),
      Gaps.vGap10,
      Center(
        child: Text(
          '${DeerLocalizations.of(context)!.playerAvatar.nullSafe}',
          style: Theme.of(context)
              .textTheme
              .titleSmall
              ?.copyWith(fontSize: Dimens.font_sp14),
        ),
      ),
      Gaps.vGap16,
      Gaps.vGap32,
      Padding(
        padding: EdgeInsets.only(left: 16.0),
        child: Text('${DeerLocalizations.of(context)!.playerInfomation}', style: TextStyles.textBold18),
      ),
      Gaps.vGap16,
      TextFieldItem(focusNode: _nodeText1,controller: _nickNameController, title: '${DeerLocalizations.of(context)!.playerNickname.nullSafe}', hintText: '${DeerLocalizations.of(context)!.playerNicknameTip.nullSafe}')
    ];
  }
}